package cn.szabadsag.pay.controller;

import cn.szabadsag.base.constant.JobConstants;
import cn.szabadsag.base.constant.OrderConstant;
import cn.szabadsag.order.domain.OrderAdopt;
import cn.szabadsag.order.domain.ProductOrder;
import cn.szabadsag.order.service.IOrderAdoptService;
import cn.szabadsag.order.service.IProductOrderService;
import cn.szabadsag.pay.domain.PayBill;
import cn.szabadsag.pay.service.IPayBillService;
import cn.szabadsag.quartz.service.IQuartzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付接口
 *
 * @author yangcong
 * @date 2022年03月19日 13:02
 * @since v1.0
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IOrderAdoptService orderAdoptService;

    @Autowired
    private IProductOrderService productOrderService;

    @Autowired
    private IQuartzService quartzService;

    /**
     * http://mmiu8c.natappfree.cc/pay/returnUrl?
     * charset=utf-8&
     * out_trade_no=0607159940&
     * method=alipay.trade.page.pay.return&
     * total_amount=100.00&
     * sign=oVo5CM5zm7T9bOkyc2e9woFJp7l700Cf8fxTuYC8gC9qunJ9Y8U4VpTC14LDiHjqqhM4t7zCYnFxmZ%2FpPPUrsK5zH9HtGEkcEhvr8Y%2Bnd7W93aZ7U4tpk%2Fc1jThbHSL%2F0IaBP%2F9oqKKgdJdp%2Bkl3MtYkfdu5obotk2LM3gPbL1Mkj5Y1yHR9fFthg91wiv%2Fc0VQ0bJLhXtEMn9010kkVqfXWM0Fok6uA0OabLPxs%2FXlmJwpRs0KLJvEgl8FwZ6DCAmRIIvQE7qv7tOGDBeD2nCBgMQurTg5zHxncGtpV6V8zNpInXCkx6pu2MD8yJB%2FSp8LtObCDy2h3I95Zxq8H6A%3D%3D&
     * trade_no=2022031922001458060501497153&
     * auth_app_id=2021000119642344&
     * version=1.0&
     * app_id=2021000119642344&
     * sign_type=RSA2&
     * seller_id=2088621958094718&
     * timestamp=2022-03-19+14%3A59%3A03
     */

    @RequestMapping("/notifyUrl")
    //  不走视图解析器
    @ResponseBody
    public String notifyUrl(HttpServletRequest request){
        System.out.println("-------------------异步通知---------------------");
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            //  验签
            //boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

            /* 实际验证过程建议商户务必添加以下校验：
            1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if (trade_status.equals("TRADE_SUCCESS")){
                //  1.根据商户订单号查找PayBill
                PayBill payBill = payBillService.loadByOrderSn(out_trade_no);
                //  2.填充payBill表里的信息  状态 更新时间支付订单号
                payBill.setState(1);
                payBill.setUpdateTime(new Date());
                payBill.setUnionPaySn(trade_no);
                //  3.更新payBill表中的数据
                payBillService.update(payBill);
                switch (payBill.getBusinessType()){
                    case OrderConstant.ORDER_ADOPT:
                        //  4.根据业务类型查询对应的订单
                        OrderAdopt orderAdopt = orderAdoptService.loadById(payBill.getBusinessKey());
                        //  5.修改订单状态和支付单号
                        orderAdopt.setState(1);
                        orderAdopt.setPaySn(trade_no);
                        orderAdoptService.update(orderAdopt);

                        //  支付成功 需要删除订单 取消定时任务
                        String jobName = JobConstants.ADOPT_ORDER_CANCEL_PREFIX + orderAdopt.getId();
                        quartzService.delJob(jobName);
                        System.out.println(jobName + "被取消了!");
                        break;
                    case OrderConstant.ORDER_GOODS:

                        break;
                    case OrderConstant.ORDER_PRODUCT:
                        //  4.根据业务类型查询对应的订单
                        ProductOrder productOrder = productOrderService.loadById(payBill.getBusinessKey());
                        //  5.修改订单状态和支付单号
                        productOrder.setState(1);
                        productOrder.setPaySn(trade_no);
                        //  销量+1
                        productOrderService.update(productOrder);

                        //  支付成功 需要删除订单 取消定时任务
                        String jobName1 = JobConstants.PRODUCT_ORDER_CANCEL_PREFIX + productOrder.getId();
                        quartzService.delJob(jobName1);
                        System.out.println(jobName1 + "被取消了!");
                        break;
                }
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            //验证失败
            return "fail";
        }
    }

    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request){
        System.out.println("-------------------同步通知---------------------");
        try {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //  1.根据商户订单号查找PayBill
            PayBill payBill = payBillService.loadByOrderSn(out_trade_no);

            //  支付成功之后跳转页面
            return "redirect:http://127.0.0.1:80/success.html?id=" + payBill.getBusinessKey();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }


}
